#include "Spark/Net/TcpServer.h"
#include "Spark/Net/EventLoop.h"
#include "Spark/Net/Socket.h"
#include "Spark/Utils/Logger.h"
#include "Spark/Utils/Date.h"
#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>

void onConnection(const TcpConnectionPtr& conn)
{
    if (conn->connected())
    {
        conn->setTcpNoDelay(1);
    }
}

void onMessage(const TcpConnectionPtr& conn, MsgBuffer* buf, TimePoint)
{
    conn->send(buf);
}

int main(int argc, char* argv[])
{
    if (argc < 4)
    {
        fprintf(stderr, "Usage: server <address> <port> <threads>\n");
    }
    else
    {
        wb::Logger::setLogLevel(wb::Logger::LogLevel::kDebug);

        const char* ip = argv[1];
        uint16_t port = static_cast<uint16_t>(atoi(argv[2]));
        SocketAddr listenAddr(ip, port);
        int threadCount = atoi(argv[3]);

        EventLoop loop;

        TcpServer server(&loop, listenAddr, "PingPong");

        server.setConnectionCallback(onConnection);
        server.setRecvMessageCallback(onMessage);

        if (threadCount < 1)
        {
            exit(-1);
        }
        server.setIoLoopNum(threadCount);

        server.start();

        loop.loop();
    }
}